﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Xml;
using SilverlightRestServices.Channels;

namespace FlickrSL.Channels
{
    internal class FlickrServiceMessageInspector : IClientMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, Object correlationState)
        {
            RestMessageProperty restMessage = (RestMessageProperty)reply.Properties[RestMessageProperty.Name];

            using (XmlReader reader = XmlReader.Create(restMessage.MessageData))
            {
                reader.MoveToContent();
                if (reader.IsStartElement("rsp") && reader.HasAttributes)
                {
                    if (reader.MoveToAttribute("stat"))
                    {
                        if (String.Equals("fail", reader.Value, StringComparison.OrdinalIgnoreCase))
                        {
                            reader.ReadStartElement();
                            if (reader.IsStartElement("err"))
                            {
                                FlickrServiceException ex = new FlickrServiceException(reader.GetAttribute("msg"), Int32.Parse(reader.GetAttribute("code")));
                                throw new FaultException<FlickrServiceException>(ex, new FaultReason(ex.Message), new FaultCode(ex.ErrorCode.ToString()), null);
                            }
                        }
                    }
                }
            }

            restMessage.MessageData.Position = 0;
        }

        public Object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // Add API Key and Auth Token to Query String
            HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
            if (!String.IsNullOrEmpty(FlickrSecurity.ApiKey))
            {
                if (!String.IsNullOrEmpty(httpRequest.QueryString))
                {
                    httpRequest.QueryString += "&";
                }
                else
                {
                    httpRequest.QueryString = "";
                }

                httpRequest.QueryString += "api_key=" + FlickrSecurity.ApiKey;
            }

            if (!String.IsNullOrEmpty(FlickrSecurity.AuthToken))
            {
                if (!String.IsNullOrEmpty(httpRequest.QueryString))
                {
                    httpRequest.QueryString += "&";
                }
                else
                {
                    httpRequest.QueryString = "";
                }

                httpRequest.QueryString += "auth_token=" + FlickrSecurity.AuthToken;
            }

            if (FlickrSecurity.CanSignRequest)
            {
                httpRequest.QueryString = FlickrSecurity.OnSignRequest(httpRequest.QueryString);
            }

            return null;
        }
    }
}
